<template>
    <n-form ref="formRef" :model="formValue" label-placement="left" :rules="rules" :label-width="80">
        <n-form-item label="工号" path="username">
            <n-input v-model:value="formValue.username" disabled />
        </n-form-item>
        <n-form-item label="姓名" path="nickname">
            <n-input v-model:value="formValue.nickname" placeholder="请输入姓名" />
        </n-form-item>
        <n-form-item label="性别" path="gender">
            <n-radio-group v-model:value="formValue.gender" name="gender">
                <n-space>
                    <n-radio :key="'1'" :value="'1'">男</n-radio>
                    <n-radio :key="'2'" :value="'2'">女</n-radio>
                </n-space>
            </n-radio-group>
        </n-form-item>
        <n-form-item label="手机号" path="mobile">
            <n-input v-model:value="formValue.mobile" placeholder="请输入手机号" />
        </n-form-item>
        <n-form-item label="电子邮箱" path="email">
            <n-input v-model:value="formValue.email" placeholder="请输入电子邮箱" />
        </n-form-item>
        <n-form-item>
            <n-space :style="{ marginLeft: '80px' }">
                <n-button attr-type="button" type="primary" @click="handleSubmit"> 确定 </n-button>
            </n-space>
        </n-form-item>
    </n-form>
</template>

<script setup lang="ts">
import { api } from "@/api/ucenter"
import { FormInst, FormRules } from "naive-ui"

const formRef = ref<FormInst | null>(null)

const formValue = ref<Recordable>({})

const rules: FormRules = {
    nickname: [{ required: true, message: "请输入姓名" }]
}

async function loadData() {
    const { res, isOk } = await api.profile()
    if (isOk()) {
        const v = res.value ?? {}
        formValue.value = {
            username: v.username,
            nickname: v.nickname,
            gender: v.gender,
            mobile: v.mobile
        }
    }
}

loadData()

const handleSubmit = () => {
    formRef.value?.validate(async errors => {
        if (!errors) {
            await api.updateProfile({ ...formValue.value })
        } else {
            console.log(errors)
        }
    })
}
</script>
